<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <!-- 基本信息 -->
        <a-row :gutter="48">
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
              <a-input
                :max-length="255"
                :disabled="formDisabled"
                v-model="model.bpmBizTitle"
                placeholder="请输入流程名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="单据编号">
              <a-input placeholder="请输入单据编号" v-model="model.billNo" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createBy">
              <!-- <select-user-by-dep :multi="false" v-model="model.handlerId" disabled /> -->
              <j-select-user-by-dep v-model="model.createBy" :multi="false" disabled></j-select-user-by-dep>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sysOrgCode">
              <!-- <j-select-depart v-model="model.handlerDeptId" disabled /> -->
              <j-select-depart v-model="model.sysOrgCode" :trigger-change="true" disabled customReturnField="orgCode" :multi="true"></j-select-depart>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="项目信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <SelectProjectDistributionInput
                    :disabled="formDisabled"
                    projectStatus="2"
                    :proDisabled="true"
                    :isContractManager="true"
                    v-model="model.projectId"
                    placeholder="请选择项目名称"
                    @input="onChangeProjectName"></SelectProjectDistributionInput>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="finalNo">
                  <a-input disabled v-model="model.finalNo" placeholder="请输入项目编号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamName">
                  <select-team-input disabled v-model="model.teamName" :tdlx="1" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="undertaker">
                  <select-user-by-dep disabled v-model="model.undertaker" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="立项日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectEstablishDate">
                  <j-date
                    disabled
                    placeholder="请选择立项日期"
                    v-model="model.projectEstablishDate"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signUnit">
                  <select-Company-input placeholder="请输入签订单位" disabled v-model="model.signUnit" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.year"
                    dictCode="yjgsnd"
                    placeholder="请选择业绩归属年度" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ownerUnit">
                  <select-customer-input disabled v-model="model.ownerUnit" commercialType="1" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contacts">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.contacts"
                    :dictCode="cust_lxr"
                    placeholder="请选择联系人" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contactTel">
                  <a-input disabled v-model="model.contactTel" placeholder="请输入联系电话"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item prop="areaCode" label="项目所在地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <AddressChoice disabled type="cascader" v-model="model.areaCode" placeholder="请输入省市区" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item prop="projectAddress" label="项目详细地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input disabled v-model="model.projectAddress" placeholder="请输入项目详细地址"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目来源" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectSource">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.projectSource"
                    dictCode="xmly_type"
                    placeholder="请选择项目来源" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="预计合同额(元)"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="estimatedContractAmount">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.estimatedContractAmount"
                    placeholder="请输入预计合同额"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="预计合同额大写"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="estimatedContractcapitalChineseAmount">
                  <a-input
                    disabled
                    v-model="model.estimatedContractcapitalChineseAmount"
                    placeholder="请输入预计合同额大写"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="立项事由及说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="establishReason">
                  <a-textarea
                    :max-length="500"
                    disabled
                    v-model="model.establishReason"
                    rows="4"
                    placeholder="请输入立项事由及说明" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="项目附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
                  <j-upload v-if="!formDisabled" disabled v-model="model.attachment"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.attachment)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="任务信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <!-- @back="changeTask" -->
                <a-form-model-item label="任务编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskId">
                  <SelectTaskFileInput
                    customDistributionType="producting"
                    :disabled="formDisabled"
                    v-model="model.taskId"
                    :projectId="model.projectId"
                    @input="onTaskIdInput" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业务分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryCode">
                  <business-category-name-select
                    :disabled="formDisabled"
                    v-model="model.categoryCode"
                    @back="handleCategoryCode"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同占比(%)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractRate">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractRate"
                    placeholder="请输入合同占比"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同分配额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractAmount">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractAmount"
                    placeholder="请输入合同分配额"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="切割合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cutContractAmount">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.cutContractAmount"
                    placeholder="请输入切割合同额"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productTeam">
                  <select-team-input
                    :disabled="taskPaymentDisabled"
                    v-model="model.productTeam"
                    :tdlx="2"
                    :isChooseModal="true"
                    :triggerChange="true"
                    @back="handleProductTeamBack" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="生产公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productCompanyId">
                  <select-Company-input :disabled="formDisabled" placeholder="请选择生产公司" v-model="model.productCompanyId" disabled />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="任务类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskType">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.taskType"
                    dictCode="task_type"
                    placeholder="请选择任务类型" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="实施部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="executeDepart">
                  <j-select-depart :disabled="formDisabled || isChangeProductTeam" v-model="model.executeDepart" @input="onExecuteDepartInput" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="部门负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="minister">
                  <select-user-by-dep v-model="model.minister" multi :disabled="formDisabled || isChangeProductTeam" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectLeading">
                  <select-user-by-dep v-model="model.projectLeading" :disabled="formDisabled || isChangeProductTeam" @back="handleProjectLeadingBack" />
                </a-form-model-item>
              </a-col>

              <!-- 当任务类型为环评咨询，水保咨询时，展示本项 -->
              <template v-if="model.taskType == 1 || model.taskType == 4">
                <a-col :span="8" v-if="model.taskType == 1">
                  <a-form-model-item label="审核工程师" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalEngineer">
                    <select-user-by-dep v-model="model.approvalEngineer" :disabled="formDisabled || isChangeProductTeam" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="审批级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalLevel">
                    <j-dict-select-tag
                      :disabled="formDisabled || isChangeProductTeam"
                      type="list"
                      v-model="model.approvalLevel"
                      dictCode="approval_level"
                      placeholder="请选择审批级别" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    label="审批系数"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="approvalCoefficient">
                    <a-input-number
                      :precision="1"
                      :disabled="formDisabled || isChangeProductTeam"
                      v-model="model.approvalCoefficient"
                      placeholder="请输入审批系数"
                      :min="0"
                      :max="99999"
                      style="width: 100%;" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="行业类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="industryCategory">
                    <j-dict-select-tag
                      :disabled="formDisabled || isChangeProductTeam"
                      type="list"
                      v-model="model.industryCategory"
                      dictCode="	industry_category"
                      placeholder="请选择行业类别" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    label="行业系数"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="industryCoefficient">
                    <a-input-number
                      :precision="1"
                      :disabled="formDisabled || isChangeProductTeam"
                      v-model="model.industryCoefficient"
                      placeholder="请输入行业系数"
                      :min="0"
                      :max="99999"
                      style="width: 100%;" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="复杂程度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="complexity">
                    <j-dict-select-tag
                      :disabled="formDisabled || isChangeProductTeam"
                      type="list"
                      v-model="model.complexity"
                      dictCode="industry_coefficient"
                      placeholder="请选择复杂程度" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="复杂系数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="complexCoefficient">
                    <a-input-number
                      :precision="1"
                      :disabled="formDisabled || isChangeProductTeam"
                      v-model="model.complexCoefficient"
                      placeholder="请输入复杂系数"
                      :min="0"
                      :max="99999"
                      style="width: 100%;" />
                  </a-form-model-item>
                </a-col>
              </template>

              <!-- 当任务类型为检验检测时，展示本项 -->
              <template v-if="model.taskType == 2">
                <a-col :span="8">
                  <a-form-model-item label="是否出具报告" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isOutReport">
                    <!-- @input="isTeamworkChange" -->
                    <j-dict-select-tag
                      :disabled="formDisabled || isChangeProductTeam"
                      type="radio"
                      v-model="model.isOutReport"
                      dictCode="YES_OR_NO"
                      placeholder="请选择是否出具报告" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    label="费用核算方式"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="expenseAccountingMethod">
                    <j-dict-select-tag
                      :disabled="formDisabled || isChangeProductTeam"
                      type="list"
                      v-model="model.expenseAccountingMethod"
                      dictCode="expense_accounting_method"
                      placeholder="请选择费用核算方式" />
                  </a-form-model-item>
                </a-col>
              </template>
              <a-col :span="24">
                <a-form-model-item label="说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="instruction">
                  <a-textarea
                    :max-length="500"
                    :disabled="formDisabled"
                    v-model="model.instruction"
                    rows="4"
                    placeholder="请输入说明" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="任务附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskFile">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.taskFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.taskFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="项目成员">
            <a-row :gutter="48">
              <a-col :span="24">
                <div v-if="!formDisabled && !isChangeProductTeam" style="margin-bottom: 6px;margin-top: 6px">
                  <a-button @click="handleMemberAdd" type="primary">新增</a-button>
                </div>
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  :loading="memberLoading"
                  :columns="memberColumns"
                  bordered
                  :components="draggableComponent"
                  :pagination="false"
                  :data-source="model.distributionDtList"
                  :scroll="{ x: scrollX }">
                  <span slot="action" slot-scope="text, record,index">
                    <template v-if="!formDisabled && !isChangeProductTeam">
                      <a-button type="link" size="small" @click="handleMemberEdit(record, index)">编辑</a-button>
                      <a-divider type="vertical" v-if="!record.isProjectLeading" />
                      <a-popconfirm title="确定删除吗?" v-if="!record.isProjectLeading" @confirm="() => handleMemberDelete(record, text, index)">
                        <a-button type="link" size="small">删除</a-button>
                      </a-popconfirm>
                    </template>
                  </span>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="4" header="项目预算">
            <a-row :gutter="48">
              <a-col :span="8">
                <!-- model.expectWorkTime -->
                <a-form-model-item label="预算总工时(人小时)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expectWorkTime">
                  <a-input-number
                    disabled
                    :max="9999999"
                    :min="0"
                    :precision="1"
                    v-model="expectWorkTime"
                    placeholder="请输入预算总工时"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="生产总绩效(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalProductPerformance">
                  <a-input-number
                    disabled
                    :max="9999999"
                    :min="0"
                    :precision="2"
                    v-model="totalProductPerformance"
                    placeholder="请输入生产总绩效"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <!-- model.workCost -->
                <a-form-model-item label="人工总成本(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workCost">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="workCost"
                    placeholder="请输入人工总成本"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="委外费(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outsourcingFee">
                  <a-input-number
                    :disabled="formDisabled || isChangeProductTeam"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.outsourcingFee"
                    placeholder="请输入委外费"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="差旅费(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="travelFee">
                  <a-input-number
                    :disabled="formDisabled || isChangeProductTeam"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.travelFee"
                    placeholder="请输入差旅费"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="专家评审费(元)"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="professionReviewFee">
                  <a-input-number
                    :disabled="formDisabled || isChangeProductTeam"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.professionReviewFee"
                    placeholder="请输入专家评审费"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="其他成本(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherCost">
                  <a-input-number
                    :disabled="formDisabled || isChangeProductTeam"
                    :max="99999999"
                    v-model="model.otherCost"
                    :precision="2"
                    placeholder="请输入其他成本"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="项目预算合计(元)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <!-- model.totalProjectBudget -->
                  <a-input-number
                    disabled
                    :max="99999999"
                    v-model="totalProjectBudget"
                    :precision="2"
                    placeholder="人工总成本+委外费+差旅费+专家评审费+其他成本"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <template v-if="model.categoryName">
                <a-col :span="24" v-if="isProjectInformation">
                  <a-form-model-item label="项目预算表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectBudgetFile">
                    <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.projectBudgetFile"></j-upload>
                    <a-button v-else icon="download" @click="viewFile(model.projectBudgetFile)">文件列表</a-button>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24" v-else>
                  <a-form-model-item label="生产绩效表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productBudgetFile">
                    <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.productBudgetFile"></j-upload>
                    <a-button v-else icon="download" @click="viewFile(model.productBudgetFile)">文件列表</a-button>
                  </a-form-model-item>
                </a-col>
              </template>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="5" header="任务进度">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="进度模板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateId">
                  <select-process-template-input
                    :disabled="taskPaymentDisabled || isChangeProductTeam"
                    :categoryName="model.categoryCode"
                    v-model="model.templateId"
                    :templateName.sync="model.templateName"
                    placeholder="请选择进度模板"
                    :multi="false"
                    @input="getTemplateList" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="允许添加子节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isAddChildNode">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.isAddChildNode"
                    disabled
                    dictCode="yes_no"
                    placeholder="请选择允许添加子节点"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="收入确认方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmIncomeMethod">
                  <j-dict-select-tag disabled type="list" v-model="model.confirmIncomeMethod" dictCode="confirm_income_method" placeholder="请选择收入确认方式" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <!-- :loading="memberLoading" -->
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  :pagination="false"
                  :loading="templateLoading"
                  :columns="templateColumns"
                  :data-source="templateDataList"
                  :scroll="{ x: true }">
                  <template slot="titleSlot" slot-scope="text">
                    <span v-if="text">
                      {{ text }}%
                    </span>
                    <span v-if="!text">
                      -
                    </span>
                  </template>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="6" header="款项进度">
            <a-row :gutter="48">
              <a-col :span="24">
                <!-- progressNodeVoList -->
                <!-- :locale="tableNoData" -->
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  bordered
                  :columns="paymentProgressColumns"
                  :components="draggableComponentOther"
                  :pagination="false"
                  :data-source="progressNodeVoList"
                  :loading="progressNodeVoLoading"
                  :scroll="{ x: scrollXOther }">
                  <span slot="action" slot-scope="text, record">
                    <a-button v-if="!formDisabled && !isChangeProductTeam" :disabled="record.shouldPayFlag == '1'" type="link" @click="handlerPaymentEdit(record)">完善</a-button>
                    <a-button type="link" @click="handlerPaymentInfo(record)">查看</a-button>
                  </span>
                </a-table>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="履约保证金(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bail">
                  <a-input-number
                    :precision="2"
                    v-model="model.bail"
                    placeholder="请输入履约保证金"
                    disabled
                    :min="0"
                    :max="999999999"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <template v-if="Number(model.bail)">
                <a-col :span="16">
                  <a-form-model-item label="款项节点说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentDesc">
                    <a-textarea
                      :disabled="formDisabled || isChangeProductTeam"
                      :max-length="200"
                      v-model="model.paymentDesc"
                      rows="4"
                      placeholder="请输入款项节点说明" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8" v-if="Number(model.bail)">
                  <a-form-model-item
                    label="是否应收"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="isCollectionPayment">
                    <j-dict-select-tag
                      :disabled="formDisabled || isChangeProductTeam"
                      type="radio"
                      v-model="model.isCollectionPayment"
                      dictCode="YES_OR_NO"
                      @input="val => val == 0 && (model.collectionDate = null)" />
                  </a-form-model-item>
                </a-col>
              </template>

              <a-col :span="8" v-if="model.isCollectionPayment == 1">
                <a-form-model-item label="预计应收日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collectionDate">
                  <j-date
                    :disabled="formDisabled || isChangeProductTeam"
                    placeholder="请选择预计应收日期"
                    v-model="model.collectionDate"
                    date-format="YYYY-MM-DD"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>

            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list
        v-if="formBpm && model.bpmStatus !== '1'"
        :formData="formData"
        style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button
          type="primary"
          v-if="formBpm"
          :style="{ marginRight: showFlowSubmitButton ? '10px' : '0px' }"
          @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpMyOmcTaskPaymentModal ref="paymentForm" @ok="memberModalFormOk" :templateDataList="templateDataList">
    </ErpMyOmcTaskPaymentModal>
    <ErpOmcTaskChangeFormPrint
      v-if="formBpm"
      id="printContent"
      class="print_style"
      :formData="model"
      :formDataHistory="formData"></ErpOmcTaskChangeFormPrint>
    <EditTaskModal
      ref="editTaskModal"
      :model="model"
      :templateDataList="templateDataList"
      @AddMember="AddMember"
      :disabled="formDisabled"
      @PerfectTaskChange="PerfectTaskChange">
    </EditTaskModal>
  </a-spin>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import {
  filterMultiDictText,
  initDictOptions
} from '@/components/dict/JDictSelectUtil'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import AddressChoice from '@/components/AddressChoice/AddressChoice';
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';

import SelectTaskFileInput from '@/views/scy/components/SelectTaskFileInput'; //  任务编号
import SelectProcessTemplateInput from '@/views/scy/components/SelectProcessTemplateInput' // 进度模板
import Decimal from 'decimal.js'
import ErpOmcTaskChangeFormPrint from './ErpOmcTaskChangeFormPrint.vue'
import { DragResizable } from '@/mixins/DragResizable'
import BusinessCategoryNameSelect from '@views/erp/components/BusinessCategoryNameSelect'
export default {
  name: 'ErpProgressTaskChangeListForm',
  mixins: [DisabledAuthFilterMixin, viewFile, DragResizable],
  components: {
    SelectProjectDistributionInput: () => import('@/views/scy/components/SelectProjectDistributionInput.vue'), // 项目名称
    ViewFileModal,
    SelectUserByDep,
    SelectTeamInput,
    SelectCustomerInput,
    AddressChoice,
    SelectCompanyInput,
    CommonFlowList,
    SelectTaskFileInput,
    SelectProcessTemplateInput,
    ErpMyOmcTaskPaymentModal: () => import('../reference/ErpMyOmcTaskPaymentModal'), // 款项计划
    EditTaskModal: () => import('./editTaskModal.vue'),
    BusinessCategoryNameSelect,
    ErpOmcTaskChangeFormPrint
},
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    taskId: {
      type: String,
      default: '',
      required: false
    },
    projectNameId: {
      type: String,
      default: '',
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    isShowcutContractAmount:{
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      memberLoading: false,
      isChangeProductTeam: false, // 是否切换生产团队
      oldProductTeam: '', // 旧的生产团队
      activeKey: ['1', '2', '3', '4', '5', '6'],
      tableNoData: {
        emptyText: () => (
          <a-empty description="合同未签订，暂无数据" />
        )
      },
      templateLoading: false,
      progressNodeVoLoading: false,

      model: {
        distributionDtList: [],
        dataSource: [],
        handlerId: undefined,
        handlerDeptId: undefined,
        createTime: undefined,
        undertaker: undefined,
        projectId: ''
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      templateDataList: [], // 进度模板列表
      progressNodeVoList: [], // 款项进度列表
      confirmLoading: false,
      validatorRules: {
        projectId: [
          { required: true, message: '请选择项目名称!', pattern: '[^ \x22]+' }
        ],
        taskType: [
          { required: true, message: '请选择任务类型!' }
        ],
        taskId: [
          { required: true, message: '请选择任务编号!' }
        ],
        categoryCode: [
          { required: true, message: '请选择业务分类!' }
        ],
        productTeam: [
          { required: true, message: '请选择生产团队!' }
        ],
        outsourcingFee: [
          { required: true, message: '请输入委外费!' }
        ],
        travelFee: [
          { required: true, message: '请输入差旅费!' }
        ],
        professionReviewFee: [
          { required: true, message: '请输入专家评审费!' }
        ],
        otherCost: [
          { required: true, message: '请输入其他成本!' }
        ],
        collectionDate: [
          { required: true, message: '请选择预计应收日期!' }
        ],
        executeDepart: [
          { required: true, message: '请选择实施部门!' }
        ],
        minister: [
          { required: true, message: '请选择部门负责人!' }
        ],
        projectLeading: [
          { required: true, message: '请选择项目负责人!' }
        ],
        approvalEngineer: [
          { required: true, message: '请选择审核工程师!' }
        ],
        approvalLevel: [
          { required: true, message: '请选择审批级别!' }
        ],
        approvalCoefficient: [
          { required: true, message: '请输入审批系数!' }
        ],
        industryCategory: [
          { required: true, message: '请选择行业类别!' }
        ],
        industryCoefficient: [
          { required: true, message: '请输入行业系数!' }
        ],
        complexity: [
          { required: true, message: '请选择复杂程度!' }
        ],
        complexCoefficient: [
          { required: true, message: '请输入复杂系数!' }
        ],
        isOutReport: [
          { required: true, message: '请选择是否出具报告!' }
        ],
        wrapperCol: [
          { required: true, message: '请选择费用核算方式!' }
        ],
        isCollectionPayment: [
          { required: true, message: '请选择是否应收!' }
        ]
      },
      url: {
        add: '/api/erp/omc/task/erpOmcTaskDistribution/add',
        edit: '/api/erp/omc/task/erpOmcTaskDistribution/edit',
        queryById: '/api/erp/omc/task/erpOmcTaskDistribution/queryById',
        erpOmcProjectQueryById: '/api/erp/omc/project/erpOmcProject/queryById',
        queryPageList: '/api/erp/omc/project/erpOmcProjectTaskFinal/queryPageList',
        generatedFormNumber: '/api/erp/base/generatedFormNumber'
      },
      loading: false,
      memberColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '项目成员',
          align: 'center',
          dataIndex: 'projectMember',
          width: 100,
          ellipsis: true,
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['projectMember'], text + '')
            }
          }
        },
        {
          title: '分配合同额(元)',
          align: 'center',
          dataIndex: 'contractAmount',
          width: 140,
          ellipsis: true
        },
        {
          title: '合同额占比(%)',
          align: 'center',
          dataIndex: 'contractRate',
          width: 135,
          ellipsis: true
        },
        {
          title: '工时单价(元)',
          align: 'center',
          dataIndex: 'dayCost',
          width: 120,
          ellipsis: true
        },
        {
          title: '预算工时(小时)',
          align: 'center',
          dataIndex: 'expectWorkTime',
          width: 120,
          ellipsis: true
        },
        {
          title: '项目绩效(元)',
          align: 'center',
          dataIndex: 'projectPerformance',
          width: 120,
          ellipsis: true
        },
        {
          title: '人工成本(元)',
          align: 'center',
          dataIndex: 'laborCost',
          width: 120,
          ellipsis: true
        },
        {
          title: '操作',
          align: 'center',
          fixed: 'right',
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 进度列表
      templateColumns: [
        {
          title: '顺序',
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '节点名称',
          align: 'center',
          dataIndex: 'nodeName'
        },
        {
          title: '节点进度',
          align: 'center',
          dataIndex: 'nodeProgress',
          scopedSlots: { customRender: 'titleSlot' }
        },
        {
          title: '完成状态',
          align: 'center',
          dataIndex: 'taskCompleteStatus_dictText'
        },
        {
          title: '完成时间',
          align: 'center',
          dataIndex: 'completeTime'
        },
        {
          title: '收入确认节点',
          align: 'center',
          dataIndex: 'isConfirmIncomeNode_dictText'
        }
      ],

      // 款项进度
      paymentProgressColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '款项名称',
          align: 'center',
          ellipsis: true,
          width: 200,
          dataIndex: 'nodeName'
        },
        {
          title: '金额(元)',
          align: 'center',
          ellipsis: true,
          width: 144,
          dataIndex: 'paymentMoney'
        },
        {
          title: '款项节点说明',
          align: 'center',
          ellipsis: true,
          width: 200,
          dataIndex: 'nodeDesc'
        },
        // {
        //   title: '应收日期',
        //   align: 'center',
        //   ellipsis: true,
        //   dataIndex: 'collectionDate'
        // },
        // {
        //   title: '是否关联任务',
        //   align: 'center',
        //   ellipsis: true,
        //   width: 144,
        //   customRender: (text) => {
        //     if (text === '' || text === null || text === undefined) {
        //       return ''
        //     } else {
        //       return text == 0 ? '否' : '是'
        //     }
        //   },
        //   dataIndex: 'isRelatedTask'
        // },
        // {
        //   title: '是否关联进度',
        //   align: 'center',
        //   ellipsis: true,
        //   width: 144,
        //   customRender: (text) => {
        //     if (text === '' || text === null || text === undefined) {
        //       return ''
        //     } else {
        //       return text == 0 ? '否' : '是'
        //     }
        //   },
        //   dataIndex: 'isRelatedTaskNode'
        // },
        {
          title: '本任务关联款项金额(元)',
          align: 'center',
          ellipsis: true,
          width: 200,
          dataIndex: 'taskPaymentMoney'
        },
        {
          title: '任务进度',
          align: 'center',
          ellipsis: true,
          width: 200,
          dataIndex: 'taskNodeId_dictText'
        },
        {
          title: '节点进度(%)',
          align: 'center',
          ellipsis: true,
          width: 144,
          dataIndex: 'taskProgress'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      dictOptions: {},
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=0',
      memberEditIndex: 0
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    // 判断生产团队和任务进度模板的禁用
    taskPaymentDisabled () {
      if (this.formDisabled) {
        return this.formDisabled
      } else {
        // 判断progressNodeVoList数组中有无shouldPayFlag 等于1的等于1则返回true，否则返回false
        if (this.progressNodeVoList && this.progressNodeVoList.length > 0) {
          const shouldPayFlag = this.progressNodeVoList.some(item => item.shouldPayFlag == '1')
          if (shouldPayFlag) {
            return true
          } else {
            return false
          }
        } else {
          return false
        }
      }
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
    // 总工时
    expectWorkTime() {
      const { distributionDtList } = this.model
      if (!distributionDtList || !distributionDtList.length) return 0;

      return this.model.distributionDtList.reduce((total, cur) => {
        return total + (Number(cur.expectWorkTime) || 0)
      }, 0)
    },
    // 总人工成本
    workCost() {
      const { distributionDtList } = this.model
      if (!distributionDtList || !distributionDtList.length) return 0;

      return distributionDtList.reduce((total, cur) => {
        return total + (Number(cur.laborCost) || 0)
      }, 0)
    },
    // 总生产绩效
    totalProductPerformance() {
      const { distributionDtList } = this.model
      if (!distributionDtList || !distributionDtList.length) return 0;

      return distributionDtList.reduce((total, cur) => {
        return total + (Number(cur.projectPerformance) || 0)
      }, 0)
    },
    // 总花费
    totalProjectBudget() {
      const { outsourcingFee, travelFee, professionReviewFee, otherCost } = this.model
      const parse = (num) => (Number(num) || 0)
      let sum = this.workCost + parse(outsourcingFee) + parse(travelFee) + parse(professionReviewFee) + parse(otherCost)
      return parseFloat(sum.toFixed(2))
    },
    // 判断是否为工程运维或者数字信息的业务分类
    isProjectInformation() {
      // 判断categoryName是否含有工程运维或者数字信息
      if (this.model.categoryName && (this.model.categoryName.indexOf('工程运维') !== -1 || this.model.categoryName.indexOf('数字信息') !== -1)) {
        return true
      } else {
        return false
      }
    }
  },

  watch: {
    'model.bail'(val) {
      if (!Number(val)) {
        this.$set(this.model, 'paymentDesc', null)
        this.$set(this.model, 'isCollectionPayment', null)
      }
    },
    activeKey(key) {
      this.$forceUpdate()
    },
    taskId: {
      handler(val) {
        if (!val) {
          return false
        }

        this.$set(this.model, 'createTime', moment().format('YYYY-MM-DD HH:mm:ss')) // 申请人
        this.$set(this.model, 'handlerId', this.userInfo().empId) // 申请人
        this.$set(this.model, 'handlerDeptId', this.userInfo().deptId) // 申请人
        this.$set(this.model, 'taskId', val) // 任务编号
        this.$set(this.model, 'createBy', this.userInfo().username)
        this.$set(this.model, 'sysOrgCode', this.userInfo().orgCode)
        this.generatedFormNumber();

        // 获取任务编号
        if (val) {
          getAction(this.url.queryPageList, { id: val }).then((res) => {
            if (res.success) {
              var event = res.result.records[0]
              this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
              this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类
              this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
              this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
              this.$set(this.model, 'taskType', event.taskType) // 默认任务类型为其他
              this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
              this.$set(this.model, 'productCompanyId', event.productCompanyId) // 生产公司
              this.$set(this.model, 'cutContractAmount', event.cutContractAmount) // 切割合同额
              this.$set(this.model, 'templateId', event.templateId)
              this.$set(this.model, 'isAddChildNode', event.isAddChildNode)
              this.$set(this.model, 'confirmIncomeMethod', event.confirmIncomeMethod)
              this.$set(this.model, 'templateName', event.templateName)

              this.$set(this.model, 'outsourcingFee', event.outsourcingFee) // 委外费
              this.$set(this.model, 'travelFee', event.travelFee) // 差旅费
              this.$set(this.model, 'professionReviewFee', event.professionReviewFee) // 专家评审费
              this.$set(this.model, 'otherCost', event.otherCost) // 其他成本

              this.$set(this.model, 'taskType', event.taskType) // 任务类型
              this.$set(this.model, 'executeDepart', event.executeDepart) // 实施部门
              this.$set(this.model, 'minister', event.minister) // 部门负责人
              this.$set(this.model, 'projectLeading', event.projectLeading) // 项目负责人
              this.$set(this.model, 'isOutReport', event.isOutReport) // 请选择是否出具报告
              this.$set(this.model, 'expenseAccountingMethod', event.expenseAccountingMethod) // 请选择费用核算方式

              this.$set(this.model, 'instruction', event.instruction)// 说明
              this.$set(this.model, 'taskFile', event.taskFile) // 文件列表
              this.$set(this.model, 'projectBudgetFile', event.projectBudgetFile || '') // 文件列表
              this.$set(this.model, 'productBudgetFile', event.productBudgetFile || '') // 文件列表

              this.$set(this.model, 'approvalEngineer', event.approvalEngineer) // 审核工程师
              this.$set(this.model, 'approvalLevel', event.approvalLevel) // 审批级别
              this.$set(this.model, 'approvalCoefficient', event.approvalCoefficient) // 审批系数
              this.$set(this.model, 'industryCoefficient', event.industryCoefficient) // 行业系数
              this.$set(this.model, 'industryCategory', event.industryCategory) // 行业类别
              this.$set(this.model, 'complexity', event.complexity) // 复杂程度
              this.$set(this.model, 'complexCoefficient', event.complexCoefficient) // 复杂系数

              this.$set(this.model, 'bail', event.bail) // 履约保证金
              this.$set(this.model, 'paymentDesc', event.paymentDesc) // 款项节点说明
              this.$set(this.model, 'isCollectionPayment', event.isCollectionPayment) // 是否应收
              this.$set(this.model, 'collectionDate', event.collectionDate) // 预计应收日期
              this.oldProductTeam = event.productTeam
              const { projectId } = event
              let taskId = val
              this.getTaskNodeList(1, '', projectId, taskId) // 获取任务进度
              this.getPaymentList(1, '', projectId, taskId) // 获取款项进度列表
              this.getMemberList(1, '', projectId, taskId)// 查看成员列表
              // this.getTaskNodeList(1, '', projectId, taskId)
              this.getTemplateId(taskId)
              this.getQueryByEntity(projectId) // 获取履约保证金
            }
          })
        }
        this.visible = true;
      },
      immediate: true
    },
    projectNameId: {
      handler(val) {
        if (!val) {
          return false
        }
        getAction(this.url.erpOmcProjectQueryById, { id: val }).then((res) => {
          if (res.success) {
            var event = res.result
            // this.queryPaymentListByProjectId(event.id) // 获取款项进度列表
            // this.getQueryByEntity(event.id) // 获取履约保证金
            this.$set(this.model, 'projectName', event.projectName) // 项目名称
            this.$set(this.model, 'projectId', val) // 项目id
            this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
            this.$set(this.model, 'teamName', event.oldTeamId ? event.oldTeamId : event.teamName) // 经营团队
            this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
            this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
            this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
            this.$set(this.model, 'year', event.year) // 业绩归属年度
            this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
            this.$set(this.model, 'contacts', event.contacts) // 联系人
            this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
            this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
            this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
            this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
            this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
            this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
            this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
            this.$set(this.model, 'attachment', event.attachment) // 项目附件
            this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + event.ownerUnit + '\'';
          }
        })
      },
      immediate: true
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData();
    // 加载数据字典信息
    this.initDictConfig();
    this.customKey = 'memberColumns'
    this.otherKey = 'paymentProgressColumns'
    this.memberColumnswidth = this.memberColumns.map(val => {
      return val.width
    })
    this.paymentProgressColumnswidth = this.paymentProgressColumns.map(val => {
      return val.width
    })
  },
  methods: {
    ...mapGetters(['userInfo']),
    // 获取单据编号
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'RWBG', subSystemCode: '05' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'billNo', res.result)
        }
      })
    },

    // 选择项目名称
    async onChangeProjectName(item) {
      var event = await item.choseObj[0]
      if (!event) {
        this.$set(this.model, 'projectName', '') // 项目名称
        this.$set(this.model, 'bail', '') // 保证金
        this.$set(this.model, 'finalNo', '') // 项目编号
        this.$set(this.model, 'teamName', '') // 经营团队
        this.$set(this.model, 'undertaker', '') // 项目承接人
        this.$set(this.model, 'projectEstablishDate', '') // 立项日期
        this.$set(this.model, 'signUnit', '') // 签订单位
        this.$set(this.model, 'year', '') // 业绩归属年度
        this.$set(this.model, 'ownerUnit', '') // 业主单位
        this.$set(this.model, 'contacts', '') // 联系人
        this.$set(this.model, 'contactTel', '') // 联系方式
        this.$set(this.model, 'areaCode', '') // 项目所在地址
        this.$set(this.model, 'projectAddress', '') // 项目所在详细地址
        this.$set(this.model, 'projectSource', '') // 项目来源
        this.$set(this.model, 'estimatedContractAmount', '') // 预计合同额
        this.$set(this.model, 'estimatedContractcapitalChineseAmount', '') // 预计合同额大写
        this.$set(this.model, 'establishReason', '') // 立项事由及说明
        this.$set(this.model, 'attachment', '') // 项目附件
        this.$set(this.model, 'taskId', '') // 任务编号

        // this.$set(this.model, 'taskType', '')// 任务类型
        // this.$set(this.model, 'executeDepart', '')// 实施部门
        // this.$set(this.model, 'minister', '')// 部门负责人
        // this.$set(this.model, 'projectLeading', '')// 项目负责人
        // this.$set(this.model, 'approvalEngineer', '')// 审核工程师
        // this.$set(this.model, 'approvalLevel', '')// 审批级别
        // this.$set(this.model, 'approvalCoefficient', '')// 审批系数
        // this.$set(this.model, 'industryCategory', '')// 行业类别
        // this.$set(this.model, 'industryCoefficient', '')// 行业系数
        // this.$set(this.model, 'complexity', '')// 复杂程度
        // this.$set(this.model, 'complexCoefficient', '')// 复杂系数

        // this.$set(this.model, 'categoryName', '') // 业务分类
        // this.$set(this.model, 'categoryCode', '') // 业务分类
        // this.$set(this.model, 'contractRate', '') // 合同占比(%)
        // this.$set(this.model, 'contractAmount', '') // 合同分配额(元)

        // this.$set(this.model, 'productTeam', '') // 生产团队
        // this.$set(this.model, 'taskId', '') // 任务编号
        // this.progressNodeVoList = [] // 清空款项进度
        // this.$set(this.model, 'instruction', '')//说明
        // this.$set(this.model, 'taskFile', '') //文件列表
        this.clearTaskMsg()

        return false
      }
      // this.queryPaymentListByProjectId(event.id) // 获取款项进度列表
      // this.queryPaymentNodeListByMainId(event.id)
      this.getQueryByEntity(event.id) // 获取履约保证金
      // this.queryTaskNodeListByMainId(event.id) //  获取任务进度
      this.$set(this.model, 'projectName', event.projectName) // 项目名称
      this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
      this.$set(this.model, 'teamName', event.oldTeamId ? event.oldTeamId : event.teamName) // 经营团队
      this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
      this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
      this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
      this.$set(this.model, 'year', event.year) // 业绩归属年度
      this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
      this.$set(this.model, 'contacts', event.contacts) // 联系人
      this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
      this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
      this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
      this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
      this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
      this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
      this.$set(this.model, 'attachment', event.attachment) // 项目附件
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + event.ownerUnit + '\'';
      this.$set(this.model, 'taskId', '') // 任务编号

      // this.$set(this.model, 'taskType', '')// 任务类型
      // this.$set(this.model, 'executeDepart', '')// 实施部门
      // this.$set(this.model, 'minister', '')// 部门负责人
      // this.$set(this.model, 'projectLeading', '')// 项目负责人
      // this.$set(this.model, 'approvalEngineer', '')// 审核工程师
      // this.$set(this.model, 'approvalLevel', '')// 审批级别
      // this.$set(this.model, 'approvalCoefficient', '')// 审批系数
      // this.$set(this.model, 'industryCategory', '')// 行业类别
      // this.$set(this.model, 'industryCoefficient', '')// 行业系数
      // this.$set(this.model, 'complexity', '')// 复杂程度
      // this.$set(this.model, 'complexCoefficient', '')// 复杂系数
      // this.$set(this.model, 'categoryName', '') // 业务分类
      // this.$set(this.model, 'categoryCode', '') // 业务分类
      // this.$set(this.model, 'contractRate', '') // 合同占比(%)
      // this.$set(this.model, 'contractAmount', '') // 合同分配额(元)

      // this.$set(this.model, 'productTeam', '') // 生产团队
      // this.$set(this.model, 'taskId', '') // 任务编号

      // // 切换清空 项目成员，项目预算，任务进度，款项进度
      // this.$set(this.model, 'distributionDtList', []) // 项目成员

      // this.$set(this.model, 'workCost', '') // 项目预算
      // this.$set(this.model, 'outsourcingFee', '') // 项目预算
      // this.$set(this.model, 'travelFee', '') // 项目预算
      // this.$set(this.model, 'professionReviewFee', '') // 项目预算
      // this.$set(this.model, 'otherCost', '') // 项目预算
      // this.$set(this.model, 'totalProjectBudget', '') // 项目预算

      // this.$set(this.model, 'templateId', '') // 任务进度
      // this.$set(this.model, 'templateDataList', [])
      // this.templateDataList = []

      // this.$set(this.model, 'progressNodeVoList', '')// 款项进度
      // this.progressNodeVoList = []

      // this.$set(this.model, 'instruction', '')//说明
      // this.$set(this.model, 'taskFile', '') //文件列表
      // this.$set(this.model, 'paymentDesc', '') //款项节点说明

      this.clearTaskMsg()
    },
    clearTaskMsg() {
      const clearArr = ['categoryName', 'categoryCode', 'contractRate', 'contractAmount',
      'cutContractAmount','productTeam', 'productCompanyId', 'taskType', 'executeDepart', 'minister', 'projectLeading',
        'isOutReport', 'approvalEngineer', 'approvalLevel', 'approvalCoefficient',
        'industryCategory', 'industryCoefficient', 'complexity', 'complexCoefficient',
        'expenseAccountingMethod', 'instruction', 'taskFile', 'distributionDtList',
        'expectWorkTime', 'workCost', 'totalProductPerformance', 'outsourcingFee', 'travelFee', 'professionReviewFee',
        'otherCost', 'totalProjectBudget', 'templateId', 'templateDataList', 'isAddChildNode', 'confirmIncomeMethod', 'bail', 'paymentDesc',
        'isCollectionPayment', 'collectionDate', 'templateName']
      clearArr.forEach(it => {
        this.$set(this.model, it, undefined)
      })
      this.templateDataList = []
      this.progressNodeVoList = []
    },

    // 选择任务编号
    onTaskIdInput(item) {
      // debugger
      var event = item.choseObj[0]
      if (!event) {
        // this.$set(this.model, 'categoryName', '') // 业务分类
        // this.$set(this.model, 'categoryCode', '') // 业务分类
        // this.$set(this.model, 'contractRate', '') // 合同占比(%)
        // this.$set(this.model, 'contractAmount', '') // 合同分配额(元)

        // this.$set(this.model, 'productTeam', '') // 生产团队
        // 切换任务信息，清空数据项
        this.clearTaskMsg()

        return false
      }
      this.getTaskNodeList(1, '', this.model.projectId, event.id) // 获取任务进度
      this.getPaymentList(1, '', this.model.projectId, event.id) // 获取款项进度
      this.getMemberList(1, '', this.model.projectId, event.id)// 查看成员
      this.getTemplateId(this.model.taskId)

      this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
      this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类
      this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
      this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
      this.$set(this.model, 'cutContractAmount', event.cutContractAmount) // 切割合同额(元)
      this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
      this.$set(this.model, 'productCompanyId', event.productCompanyId) // 生产公司
      this.oldProductTeam = event.productTeam
      this.$set(this.model, 'outsourcingFee', event.outsourcingFee) // 委外费
      this.$set(this.model, 'travelFee', event.travelFee) // 差旅费
      this.$set(this.model, 'professionReviewFee', event.professionReviewFee) // 专家评审费
      this.$set(this.model, 'otherCost', event.otherCost) // 其他成本
      this.$set(this.model, 'taskType', event.taskType) // 任务类型
      this.$set(this.model, 'executeDepart', event.executeDepart) // 实施部门
      this.$set(this.model, 'minister', event.minister) // 部门负责人
      this.$set(this.model, 'projectLeading', event.projectLeading) // 项目负责人
      this.$set(this.model, 'isOutReport', event.isOutReport) // 请选择是否出具报告
      this.$set(this.model, 'expenseAccountingMethod', event.expenseAccountingMethod) // 请选择费用核算方式

      this.$set(this.model, 'instruction', event.instruction)// 说明
      this.$set(this.model, 'taskFile', event.taskFile) // 文件列表
      this.$set(this.model, 'projectBudgetFile', event.projectBudgetFile || '') // 文件列表
      this.$set(this.model, 'productBudgetFile', event.productBudgetFile || '') // 文件列表

      this.$set(this.model, 'approvalEngineer', event.approvalEngineer) // 审核工程师
      this.$set(this.model, 'approvalLevel', event.approvalLevel) // 审批级别
      this.$set(this.model, 'approvalCoefficient', event.approvalCoefficient) // 审批系数
      this.$set(this.model, 'industryCoefficient', event.industryCoefficient) // 行业系数
      this.$set(this.model, 'industryCategory', event.industryCategory) // 行业类别
      this.$set(this.model, 'complexity', event.complexity) // 复杂程度
      this.$set(this.model, 'complexCoefficient', event.complexCoefficient) // 复杂系数

      // this.$set(this.model, 'bail', event.bail) //履约保证金
      this.$set(this.model, 'paymentDesc', event.paymentDesc) // 款项节点说明
      this.$set(this.model, 'isCollectionPayment', event.isCollectionPayment) // 是否应收
      this.$set(this.model, 'collectionDate', event.collectionDate) // 预计应收日期
    },

    // 选择业务分类
    handleCategoryCode (obj) {
      if (obj) {
        this.$set(this.model, 'categoryName', obj.categoryName)
      }
    },
    // 选择生产团队
    handleProductTeamBack (val) {
      this.isChangeProductTeam = true
      this.$set(this.model, 'productCompanyId',val[0].belongCompanyId)
      if (val && val.length > 0) {
        // 清除数据
        const clearArr = ['executeDepart', 'minister', 'projectLeading',
          'isOutReport', 'approvalEngineer', 'approvalLevel', 'approvalCoefficient',
          'industryCategory', 'industryCoefficient', 'complexity', 'complexCoefficient',
          'expenseAccountingMethod', 'instruction', 'taskFile', 'projectBudgetFile', 'productBudgetFile',
          'expectWorkTime', 'workCost', 'totalProductPerformance', 'outsourcingFee', 'travelFee', 'professionReviewFee',
          'otherCost', 'totalProjectBudget', 'templateId', 'templateDataList', 'isAddChildNode', 'confirmIncomeMethod', 'bail', 'paymentDesc',
          'isCollectionPayment', 'collectionDate', 'templateName']
        clearArr.forEach(it => {
          this.$set(this.model, it, null)
          this.$delete(this.validatorRules, it)
        })
        this.model.distributionDtList = [] // 项目成员
        this.templateDataList = []
        this.progressNodeVoList.forEach(it => {
          this.$set(it, 'taskNodeId_dictText', '')
          this.$set(it, 'taskProgress', '')
          this.$set(it, 'taskNodeId', '')
          this.$set(it, 'taskCompleteStatus', '')
          this.$set(it, 'taskCompleteStatus_dictText', '')
        })
      }
    },
    getQueryByEntity(id) {
      var params = {
        preProjectId: id,
        feeCategory: '2',
        bpmStatus: '3'
      }
      // 查看项目保证金
      getAction('/api/erp/finance/deposit/erpFinanceProjectDepositBill/queryByEntity', params).then((res) => {
        if (res.success) {
          let data = res.result
          this.$set(this.model, 'bail', data.remittanceAmount)
          // this.$set(this.validatorRules, 'collectionDate', [{ required: true, message: '请选择应收日期!' }]);
          // this.$set(this.validatorRules, 'paymentDesc', [{ required: true, message: '请填写款项节点说明!' }]);
        } else {
          this.$set(this.model, 'bail', '')
          // this.$delete(this.validatorRules, 'collectionDate');
          // this.$delete(this.validatorRules, 'paymentDesc');
        }
      })
    },

    // 获取款项进度列表
    queryPaymentListByProjectId(taskId) {
      this.progressNodeVoList = []
      getAction('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskPaymentList', { taskId }).then((res) => {
        if (res.success) {
          this.progressNodeVoList = res.result
        }
      })
    },
    // 编辑获取款项进度列表
    queryPaymentNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.progressNodeVoList = []
      this.progressNodeVoLoading = true
      getAction('/api/erp/omc/task/erpOmcTaskDistribution/queryPaymentNodeListByMainId', { id }).then((res) => {
        if (res.success) {
          this.progressNodeVoList = res.result
        } else {
          this.queryPaymentListByProjectId(this.model.taskId) // 获取款项进度列表
        }
      }).finally(() => {
        this.progressNodeVoLoading = false
      })
    },
    // 编辑获取任务进度列表
    queryTaskNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.templateLoading = true
      this.templateDataList = []
      getAction('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskNodeListByMainId', { id }).then((res) => {
        if (res.success) {
          // 清除子节点数据
          if (res.result && res.result.length > 0) {
            this.templateDataList = res.result.filter(item => (!item.isChild || item.isChild == '0'))
          }
        }
      }).finally(() => {
        this.templateLoading = false
      })
    },

    // 选择实施部门
    onExecuteDepartInput(item) {
      if (!item[0].minister) {
        this.$set(this.model, 'minister', '')
        return false
      }
      // 赋值部门负责人
      getAction('/api/erpmng/sys/api/queryUsersByUsernames', { usernames: item[0].minister }).then((res) => {
        var idsArr = []
        var ids = ''
        if (res && res.length) {
          res.map(value => {
            idsArr.push(value.empId)
          })
        }
        ids = idsArr.toString()
        this.$set(this.model, 'minister', ids)
      })
    },
    // 点击项目负责人获取数据
    handleProjectLeadingBack (item) {
      if (this.model.projectLeading) {
        this.model.distributionDtList = this.addProjectLeading(this.model.distributionDtList)
      } else {
        if (this.model.distributionDtList && this.model.distributionDtList.length) {
          // 全部置为false
          this.model.distributionDtList.forEach((item) => {
            item.isProjectLeading = false
          })
        }
      }
    },

    // 选择进度模板
    getTemplateList(data, obj) {
      this.$set(this.model, 'confirmIncomeMethod', obj.confirmIncomeMethod || '') // 收入确认方式
      this.$set(this.model, 'isAddChildNode', obj.isAddChildNode || '') // 允许添加子节点
      if (data && data.length) {
        data.map(value => {
          value.id = this.getRandomNum()
        })
        this.$set(this.model, 'isTemplateCancel', '1')
      }
      // 后端无良心，需要前端自己处理，当选择了“允许添加子节点”需要在每一个节点里面塞isAddChildNode值最后一个节点不用塞
      let isAddChildNode = obj.isAddChildNode;
      data.forEach((item, index) => {
        if (index === data.length - 1) {
          item.isAddChildNode = '0';
        } else {
          item.isAddChildNode = isAddChildNode;
        }
      });
      this.templateDataList = data
      // this.progressNodeVoList = []
      // this.$set(this.model, 'progressNodeVoList', '')// 款项进度
      this.progressNodeVoList.forEach(it => {
        this.$set(it, 'taskNodeId_dictText', '')
        this.$set(it, 'taskProgress', '')
        this.$set(it, 'taskNodeId', '')
        this.$set(it, 'taskCompleteStatus', '')
        this.$set(it, 'taskCompleteStatus_dictText', '')
      })
    },

    // 获取唯一随机数
    getRandomNum() {
      let date = (new Date()).valueOf();// 获取时间戳
      let txt = '1234567890';// 生成的随机机器码
      let len = 19;// 机器码有多少位
      let pwd = '';// 定义空变量用来接收机器码
      for (let i = 0; i < len; i++) {
        pwd += txt.charAt(Math.floor(Math.random() * txt.length));// 循环机器码位数随机填充
      }
      return date + pwd
    },

    initDictConfig() {
      initDictOptions('ywfx_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'ywfl', res.result)
        }
      })
      initDictOptions('erp_employee_file,name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'projectMember', res.result)
        }
      })
    },
    add() {
      this.$set(this.modelDefault, 'createTime', moment().format('YYYY-MM-DD HH:mm:ss')) // 申请时间
      this.$set(this.modelDefault, 'handlerId', this.userInfo().empId) // 申请人
      this.$set(this.modelDefault, 'handlerDeptId', this.userInfo().deptId) // 申请人
      this.$set(this.modelDefault, 'taskType', '3') // 默认任务类型为其他
      this.$set(this.modelDefault, 'createBy', this.userInfo().username)
      this.$set(this.modelDefault, 'sysOrgCode', this.userInfo().orgCode)
      this.templateDataList = [] // 置空
      this.progressNodeVoList = [] // 置空
      this.edit(this.modelDefault);
      // this.userName = this.userInfo().empName;// 申请人名称

      this.generatedFormNumber();
    },
    async edit(record) {
      this.isChangeProductTeam = false
      await this.$refs.form.resetFields();
      this.model = await Object.assign({}, record);
      this.cust_lxr = `erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=${record.ownerUnit}`;
      // 判断是否选择了生产团队
      if (this.model && this.model.productTeam) {
        this.oldProductTeam = this.model.productTeam
      }
      if (this.model.oldProductTeam != this.model.productTeam) {
        this.isChangeProductTeam = true
        const clearArr = ['executeDepart', 'minister', 'projectLeading',
          'isOutReport', 'approvalEngineer', 'approvalLevel', 'approvalCoefficient',
          'industryCategory', 'industryCoefficient', 'complexity', 'complexCoefficient',
          'expenseAccountingMethod', 'instruction', 'taskFile',
          'expectWorkTime', 'workCost', 'totalProductPerformance', 'outsourcingFee', 'travelFee', 'professionReviewFee',
          'otherCost', 'totalProjectBudget', 'templateId', 'templateDataList', 'isAddChildNode', 'confirmIncomeMethod', 'bail', 'paymentDesc',
          'isCollectionPayment', 'collectionDate', 'templateName']
        clearArr.forEach(it => {
          this.$delete(this.validatorRules, it)
        })
      }
      // 因为暂存的原因需要做当没有项目名称的时候需要清除不能编辑的数据，但是因为后端数据缓存的原因，所以前端这里做下处理处理方式如下：
      // 1、对于没有选择项目名称，需要清除所有不可编辑的数据和子表数据
      // 2、对于没有选择任务编号，需要清除任务携带出来的数据
      // 对于1的处理
      if (!this.model.projectId) {
        this.clearProject()
        return false
      }
      // 获取项目数据
      if (this.model.projectId) {
        this.getQueryByEntity(this.model.projectId) // 获取履约保证金
        getAction(this.url.erpOmcProjectQueryById, { id: this.model.projectId }).then((res) => {
          if (res.success) {
            var event = res.result
            this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
          }
        })
      }
       // 对于2的处理
      if (!this.model.taskId) {
        this.clearTask()
        return false
      }
      // this.queryPaymentNodeListByMainId(this.model.id) // 获取款项进度列表
      // this.queryTaskNodeListByMainId(this.model.id) // 获取任务进度列表

      if (this.model.id) {
        const { id, projectId, taskId } = this.model
        this.getTaskNodeList(2, id, projectId, taskId) // 获取任务进度
        this.getPaymentList(2, id, projectId, taskId) // 获取款项进度列表
        this.getMemberList(2, id, projectId, taskId)// 查看成员列表
        // this.getTemplateId(taskId)

        // this.memberLoading = true
        // getAction('/api/erp/omc/task/erpOmcTaskDistributionDt/list', { mainId: this.model.id })
        //   .then(response => {
        //     // this.model.distributionDtList = response.result || []
        //     this.$set(this.model, 'distributionDtList', response.result || [])
        //   }).finally(() => {
        //     this.memberLoading = false
        //   })
      }

      // // 获取任务编号
      // if (this.model.taskId) {
      //   getAction(this.url.queryPageList, { id: this.model.taskId }).then((res) => {
      //     if (res.success) {
      //       var event = res.result.records[0]
      //       this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
      //       this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
      //       this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)

      //       this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
      //     }
      //   })
      // }
      this.visible = true;
      this[this.customKey].forEach((val, index) => {
        val.width = this[this.customKey + 'width'][index]
      })
      this[this.otherKey].forEach((val, index) => {
        val.width = this[this.otherKey + 'width'][index]
      })
    },
    // 项目成员判断是否添加项目负责人，如果已添加则不添加
    addProjectLeading(distributionDtList = []) {
      // 查询项目成员列表中是否包含项目负责人，如果不包含就需要添加项目负责人
      if (distributionDtList && distributionDtList.length > 0) {
        // 先全部置为false，再判断是否包含model.projectLeading，如果不包含就添加项目负责人
        distributionDtList.forEach((item) => {
          item.isProjectLeading = false
        })
        // 循环遍历distributionDtList，判断是否包含model.projectLeading，如果不包含就添加项目负责人
        let listIndex = distributionDtList.findIndex(item => item.projectMember == this.model.projectLeading)
        if (listIndex === -1) {
          distributionDtList.unshift({
            projectMember: this.model.projectLeading, // 添加项目负责人
            id: parseInt(Math.random() * 1000000000000),
            mainId: this.mainId,
            contractAmount: null,
            contractRate: null,
            dayCost: null,
            expectWorkTime: null,
            laborCost: null,
            projectPerformance: null,
            isProjectLeading: true // 用于判断该条数据是否为项目负责人
          })
          getAction('/api/erp/files/employee/erpEmployeeFile/queryPayGradeByEmpId', { empId: this.model.projectLeading }).then(response => {
            distributionDtList[0].dayCost = response.result
          })
        } else {
          distributionDtList[listIndex].isProjectLeading = true // 用于判断该条数据是否为项目负责人
        }
      } else {
        distributionDtList.unshift({
          projectMember: this.model.projectLeading, // 添加项目负责人
          id: parseInt(Math.random() * 1000000000000),
          mainId: this.mainId,
          contractAmount: null,
          contractRate: null,
          dayCost: null,
          expectWorkTime: null,
          laborCost: null,
          projectPerformance: null,
          isProjectLeading: true // 用于判断该条数据是否为项目负责人
        })
        getAction('/api/erp/files/employee/erpEmployeeFile/queryPayGradeByEmpId', { empId: this.model.projectLeading }).then(response => {
          distributionDtList[0].dayCost = response.result
        })
      }
      return distributionDtList
    },

    clearProject() {
      this.$set(this.model, 'projectName', '') // 项目名称
      this.$set(this.model, 'bail', '') // 保证金
      this.$set(this.model, 'finalNo', '') // 项目编号
      this.$set(this.model, 'teamName', '') // 经营团队
      this.$set(this.model, 'undertaker', '') // 项目承接人
      this.$set(this.model, 'projectEstablishDate', '') // 立项日期
      this.$set(this.model, 'signUnit', '') // 签订单位
      this.$set(this.model, 'year', '') // 业绩归属年度
      this.$set(this.model, 'ownerUnit', '') // 业主单位
      this.$set(this.model, 'contacts', '') // 联系人
      this.$set(this.model, 'contactTel', '') // 联系方式
      this.$set(this.model, 'areaCode', '') // 项目所在地址
      this.$set(this.model, 'projectAddress', '') // 项目所在详细地址
      this.$set(this.model, 'projectSource', '') // 项目来源
      this.$set(this.model, 'estimatedContractAmount', '') // 预计合同额
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', '') // 预计合同额大写
      this.$set(this.model, 'establishReason', '') // 立项事由及说明
      this.$set(this.model, 'attachment', '') // 项目附件
      this.$set(this.model, 'taskId', '') // 任务编号
      this.clearTaskMsg()
    },
    clearTask() {
      // 切换任务信息，清空数据项
      this.clearTaskMsg()
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result);
          }
        });
      }
    },

    submitForm(type) {
      const that = this;
      if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          if (that.isChangeProductTeam) {
            that.submit(type)
            return false
          }
          function parse(num) {
            return Number(num) || 0
          }
          const total = this.model.distributionDtList.reduce((total, item) => {
            return new Decimal(parse(item.contractAmount)).plus(total).toNumber()
          }, 0)
          if (total !== parse(this.model.contractAmount)) {
            that.$emit('unButtonDisable')
            that.$message.warning('合同分配额总和必须等于任务委托合同额！');
            return
          }
          // 判断款项进度是否全部完善
          function isNumber(value) {
            return /^-?\d+(\.\d+)?$/.test(value);
          }
          const isPriceError = (this.progressNodeVoList || []).some(item => {
            // if (!isNumber(item.isRelatedTask)) {
            //   return true
            // }
            // if (Number(item.isRelatedTask) === 1) {
            //   if (!isNumber(item.isRelatedTaskNode)) {
            //     return true
            //   }
            //   if (!isNumber(item.isCollectionPayment)) {
            //     return true
            //   }
            // }
            // if (Number(item.isRelatedTaskNode) === 1) {
            //   if (!item.taskNodeId) {
            //     return true
            //   }
            // }
            // if (Number(item.isCollectionPayment) === 1) {
            //   if (!item.collectionDate) {
            //     return true
            //   }
            // }
            // 判断任务是否选择
            return !item.taskNodeId
          })

          if (isPriceError) {
            that.$emit('unButtonDisable')
            this.$message.warning('请完善款项进度！')
            return false
          }
          if (!this.model.distributionDtList || this.model.distributionDtList.length === 0) {
            that.$emit('unButtonDisable')
            this.$message.warning('项目成员至少有一条数据！')
            return
          }
          const isMemberError = this.model.distributionDtList.some((item) => {
            // return !item.projectMember || !item.contractAmount || !item.expectWorkTime || !item.projectPerformance
            return !item.projectMember || (item.contractAmount === undefined || item.contractAmount === null || item.contractAmount === '') || (item.expectWorkTime === undefined || item.expectWorkTime === null || item.expectWorkTime === '') || (item.projectPerformance === undefined || item.projectPerformance === null || item.projectPerformance === '')
          })
          if (isMemberError) {
            that.$emit('unButtonDisable')
            return this.$message.warning('请完善项目成员信息！')
          }
          that.submit(type)
        } else {
          that.$emit('error');
          that.$emit('unButtonDisable')
        }
      })
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
    },
    submit (type) {
      const that = this;
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        this.model.oldProductTeam = this.oldProductTeam
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }
      let model = {};
      Object.assign(model, this.model)
      model.undertakerName = model.undertaker || ''
      model.progressNodeVoList = (this.progressNodeVoList || []).map((item, index) => {
        return {
          ...item,
          sortOrder: index
        }
      }) // 款项详情
      model.progressVoList = this.templateDataList || [] // 任务进度
      model.expectWorkTime = this.expectWorkTime || null // 预计工时
      model.workCost = this.workCost || '' // 人工成本
      model.totalProductPerformance = this.totalProductPerformance || '' // 生产总绩效
      model.totalProjectBudget = this.totalProjectBudget || '' // 项目预算合计
      model.applyType = 2 // 申请传1，变更传2
      that.model.applyType = 2 // 申请传1，变更传2
      httpAction(httpurl, model, method).then(async(res) => {
        if (res.success) {
          if(type !== 'draft'){
            const verifyId = method === 'put' ? this.model.id : res.result
          const result = await getAction('/api/erp/omc/task/erpOmcTaskDistributionChange/verify',{id:verifyId},'get')
          if(!result.success) {
             that.$message.warning(result.message)
            //  that.$emit('unButtonDisable')
             that.$emit('dialogClose')
             return
          }
          }
          

          that.$message.success(res.message);
          if (method == 'post') {
            that.model.id = res.result;
          }
          that.$emit('ok', type, that.model);
        } else {
          that.$message.warning(res.message);
          that.$emit('unButtonDisable')
          that.$emit('error');
        }
      }).catch((error) => {
        that.$emit('error', error);
        that.$emit('unButtonDisable')
      }).finally(() => {
        that.confirmLoading = false;
      })
    },
    // 点击打印
    onPrint() {
      let print = new Print({
        el: '#printContent',
        popTitle: '变更任务委托详情 · 禾美环保',
        endCallback() {

        }
      })
    },
    // 子表新增
    handleMemberAdd() {
      if (!this.model.taskId) {
        return this.$message.warning('请先选择任务编号！')
      }
      this.$refs.editTaskModal.add('member');
      this.$refs.editTaskModal.title = '新增';
      this.$refs.editTaskModal.disableSubmit = false;
    },
    // 子表编辑
    handleMemberEdit(record, index) {
      this.memberEditIndex = index
      this.$refs.editTaskModal.edit(record, 'member');
      this.$refs.editTaskModal.title = '修改';
      this.$refs.editTaskModal.disableSubmit = false;
    },
    // 子表删除
    handleMemberDelete(record, text, index) {
      this.model.distributionDtList.splice(index, 1);
      // for (let i = 0; i < this.model.distributionDtList.length; i++) {
      //   if (this.model.distributionDtList[i].id == id) {
      //     this.model.distributionDtList.splice(i, 1);
      //   }
      // }
    },
    // 款项进度子表查看
    handlerPaymentInfo(record) {
      this.$refs.editTaskModal.edit(record, 'perfect');
      this.$refs.editTaskModal.title = '查看';
      this.$refs.editTaskModal.disableSubmit = true;
    },
    // 款项进度子表编辑
    handlerPaymentEdit(record) {
      this.$refs.editTaskModal.edit(record, 'perfect');
      this.$refs.editTaskModal.title = '编辑';
      this.$refs.editTaskModal.disableSubmit = false;
    },
    memberModalFormOk(data) {
      // this.memberLoading = true;
      let flag = true;
      for (let i = 0; i < this.progressNodeVoList.length; i++) {
        if (this.progressNodeVoList[i].id == data.id) {
          this.progressNodeVoList.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.progressNodeVoList.push(data);
      }
      // this.memberLoading = false;
    },
    // 新增项目成员
    AddMember(val) {
      if (this.$refs.editTaskModal.title === '新增') {
        this.model.distributionDtList.push(val)
      }
      if (this.$refs.editTaskModal.title === '修改') {
        // this.model.distributionDtList[this.memberEditIndex] = val
        this.model.distributionDtList.splice(this.memberEditIndex, 1, val)
      }
      this.$forceUpdate()
    },
    // 款项进度完善
    PerfectTaskChange(val) {
      this.progressNodeVoList.forEach((it, i) => {
        if (it.id === val.id) {
          this.progressNodeVoList.splice(i, 1, val)
        }
      })
    },
    // 获取任务进度
    getTaskNodeList(handlerType, id, projectId, taskId) {
      getAction('/api/erp/omc/task/erpOmcTaskDistributionChange/queryTaskNodeList', { handlerType, id, projectId, taskId, isChild: '0' }).then((res) => {
        if (res.success) {
          this.templateDataList = res.result || []
        }
      }).finally(() => {
        this.templateLoading = false
      })
    },
    // 获取款项进度
    getPaymentList(handlerType, id, projectId, taskId) {
      getAction('/api/erp/omc/task/erpOmcTaskDistributionChange/queryPaymentList', { projectId, id, taskId, handlerType }).then((res) => {
        if (res.success) {
          this.progressNodeVoList = res.result

          // .map(it => {
          //   return {
          //     ...it,
          //     isRelatedTask: it.isRelatedTask || '0',
          //     isRelatedTask_dictText: it.isRelatedTask_dictText || '否',
          //     isRelatedTaskNode: it.isRelatedTaskNode || '0',
          //     isRelatedTaskNode_dictText: it.isRelatedTaskNode_dictText || '否',
          //     isCollectionPayment: it.isCollectionPayment || '0',
          //     isCollectionPayment_dictText: it.isCollectionPayment_dictText || '否'
          //   }
          // })
        }
      }).finally(() => {
        this.templateLoading = false
      })
    },

    // 查看成员列表
    getMemberList(handlerType, id, projectId, taskId) {
      this.memberLoading = true
      getAction('/api/erp/omc/task/erpOmcTaskDistributionChange/queryMemberList', { projectId, id, taskId, handlerType }).then((res) => {
        if (res.success) {
          this.$set(this.model, 'distributionDtList', res.result || [])
          if (this.model.projectLeading) {
            this.model.distributionDtList = this.addProjectLeading(this.model.distributionDtList)
          } else {
            if (this.model.distributionDtList && this.model.distributionDtList.length) {
            // 全部置为false
            this.model.distributionDtList.forEach((item) => {
              item.isProjectLeading = false
            })
        }
          }
        }
      }).finally(() => {
        this.memberLoading = false
        this.templateLoading = false
      })
    },
    // 获取任务进度模板
    getTemplateId(id) {
      getAction(this.url.queryPageList, { id }).then((res) => {
        if (res.success) {
          var event = res.result.records[0]
          this.$set(this.model, 'templateId', event.templateId)
          this.$set(this.model, 'templateName', event.templateName)
          this.$set(this.model, 'confirmIncomeMethod', event.confirmIncomeMethod)
          this.$set(this.model, 'isAddChildNode', event.isAddChildNode)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.print_style {
  position: absolute;
  top: 0;
  z-index: -1111;
}

.icon {
  font-size: 45px;
}
</style>
<style>
/* @import "../../../../utils/print.css"; */
</style>
